package com.chukun.gateway.core.limiter;

import com.chukun.gateway.core.utils.JedisUtils;

/**
 * @author chukun
 * @version 1.0.0
 * @description 基于redis的分布式限流
 * @createTime 2023/12/10 21:04
 */
public class RedisDistributeCountLimiter {

    private static  final  int SUCCESS_RESULT = 1;
    private static  final  int FAILED_RESULT = 0;

    /**
     * 执行限流
     * @param key key值
     * @param limit 限制值
     * @param expire 过期时间
     * @return 是否被流控
     */
    public  boolean doFlowControl(String key,int limit,int expire){
        try {
            Object object = JedisUtils.executeScript(key,limit,expire);
            if(object == null){
                return true;
            }
            try {
                long result = Long.parseLong(object.toString());
                if (FAILED_RESULT == result) {
                    return false;
                }
            } catch (Exception e) {
                throw  new RuntimeException("分布式限流发生错误");
            }
        }catch (Exception e){
            throw  new RuntimeException("分布式限流发生错误");
        }
        return true;
    }
}
